package com.meng.mengiotmaster.module.main;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.meng.mengiotmaster.R;
import com.meng.mengiotmaster.ReallyApplication;
import com.meng.mengiotmaster.utils.DataUtils;

import cn.wch.ch34xuartdriver.CH34xUARTDriver;

public class Home2Activity extends Activity {
    public static final String TAG = "cn.wch.wchusbdriver";
    private static final String ACTION_USB_PERMISSION = "cn.wch.wchusbdriver.USB_PERMISSION";
    private ImageView iv_led_bg;
    private Button tv_switch_lamp_with;
    private Button tv_switch_color;
    private Button tv_open_srt;

    private Button tv_open_device;
    private RelativeLayout rv_home_bg_selector;
    public readThread handlerThread;
    protected final Object ThreadLock = new Object();
    private boolean isOpen;
    private Handler handler;
    private Home2Activity activity;
    public byte[] writeBuffer;
    public byte[] readBuffer;
    public int baudRate;
    public byte baudRate_byte;
    public byte stopBit;
    public byte dataBit;
    public byte parity;
    public byte flowControl;
    private int retval;
    public int totalrecv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ReallyApplication.driver = new CH34xUARTDriver(
                (UsbManager) getSystemService(Context.USB_SERVICE), this,
                ACTION_USB_PERMISSION);
        baudRate = 115200;
        stopBit = 1;
        dataBit = 8;
        parity = 0;
        flowControl = 0;
        initUI();
        if (!ReallyApplication.driver.UsbFeatureSupported())// 判断系统是否支持USB HOST
        {
            Dialog dialog = new AlertDialog.Builder(Home2Activity.this)
                    .setTitle("提示12")
                    .setMessage("您的手机不支持USB HOST，请更换其他手机再试！")
                    .setPositiveButton("确认",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface arg0,
                                                    int arg1) {
                                    System.exit(0);
                                }
                            }).create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 保持常亮的屏幕的状态
        writeBuffer = new byte[512];
        readBuffer = new byte[512];
        isOpen = false;
        activity = this;

    }

    private void initUI() {
        rv_home_bg_selector = (RelativeLayout) findViewById(R.id.rv_home_bg_selector);
        iv_led_bg = (ImageView) findViewById(R.id.iv_led_bg);
        tv_switch_lamp_with = (Button) findViewById(R.id.tv_switch_lamp_with);
        tv_switch_color = (Button) findViewById(R.id.tv_switch_color);
        tv_open_device =  (Button) findViewById(R.id.tv_open_device);
        tv_open_srt =  (Button) findViewById(R.id.tv_open_srt);
        //设置控制源码
        tv_open_srt.setEnabled(false);
        tv_open_srt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ReallyApplication.driver.SetConfig(baudRate, dataBit, stopBit, parity,//配置串口波特率，函数说明可参照编程手册
                        flowControl)) {
                    Toast.makeText(Home2Activity.this, "串口设置成功!",
                            Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(Home2Activity.this, "串口设置失败!",
                            Toast.LENGTH_SHORT).show();
                }

            }
        });
        tv_open_device.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isOpen) {
                    retval = ReallyApplication.driver.ResumeUsbList();
                    if (retval == -1)// ResumeUsbList方法用于枚举CH34X设备以及打开相关设备
                    {
                        Toast.makeText(Home2Activity.this, "打开设备失败!",
                                Toast.LENGTH_SHORT).show();
                        ReallyApplication.driver.CloseDevice();
                    } else if (retval == 0) {
                        if (!ReallyApplication.driver.UartInit()) {//对串口设备进行初始化操作
                            Toast.makeText(Home2Activity.this, "设备初始化失败!",
                                    Toast.LENGTH_SHORT).show();
                            Toast.makeText(Home2Activity.this, "打开" +
                                            "设备失败!",
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Toast.makeText(Home2Activity.this, "打开设备成功!",
                                Toast.LENGTH_SHORT).show();
                        isOpen = true;
                        iv_led_bg.setSelected(true);
                        tv_open_device.setSelected(true);
//                tv_switch_lamp_with.setText("关闭灯带");
                        tv_open_srt.setEnabled(true);
                        tv_open_srt.setSelected(true);
                        rv_home_bg_selector.setBackgroundResource(R.mipmap.bg_home_led_select);
                        new readThread().start();//开启读线程读取串口接收的数据
                    } else {

                        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                        builder.setIcon(R.mipmap.ic_launcher);
                        builder.setTitle("未授权限");
                        builder.setMessage("确认退出吗？");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                System.exit(0);
                            }
                        });
                        builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub

                            }
                        });
                        builder.show();

                    }
                } else {
                    isOpen = false;
                    tv_open_srt.setEnabled(false);
                    tv_open_device.setSelected(false);
                    tv_open_srt.setSelected(false);
                    rv_home_bg_selector.setBackgroundResource(R.color.color_030000);
                    iv_led_bg.setSelected(false);
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    ReallyApplication.driver.CloseDevice();
                    totalrecv = 0;
                }

            }
        });
        //设置控制源码
        tv_switch_lamp_with.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_switch_lamp_with.setSelected(true);
                String command = "FB 00 03 A1 A1 02 55";
                byte[] to_send = DataUtils.toByteArray(command);
                int retval = ReallyApplication.driver.WriteData(to_send, to_send.length);//写数据，第一个参数为需要发送的字节数组，第二个参数为需要发送的字节长度，返回实际发送的字节长度
                if (retval < 0)
                    Toast.makeText(Home2Activity.this, "写失败!",
                            Toast.LENGTH_SHORT).show();
            }
        });
        //设置控制源码
        tv_switch_lamp_with.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv_switch_lamp_with.setSelected(true);
                String command = "FB 00 34 B1 B1 00 10 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF 55";
                byte[] to_send = DataUtils.toByteArray(command);
                int retval = ReallyApplication.driver.WriteData(to_send, to_send.length);//写数据，第一个参数为需要发送的字节数组，第二个参数为需要发送的字节长度，返回实际发送的字节长度
                if (retval < 0)
                    Toast.makeText(Home2Activity.this, "写失败!",
                            Toast.LENGTH_SHORT).show();
            }
        });


    }

    private class readThread extends Thread {

        public void run() {
            byte[] buffer = new byte[4096];
            while (true) {
                Message msg = Message.obtain();
                if (!isOpen) {
                    break;
                }
                int length = ReallyApplication.driver.ReadData(buffer, buffer.length);
                if (length > 0) {
                    String content = DataUtils.toHexString(buffer, length * 2);
                    msg.obj = content + "";
                    handler.sendMessage(msg);
                }
            }
        }
    }

    public void onResume() {
        super.onResume();
        if (!ReallyApplication.driver.isConnected()) {
            int retval = ReallyApplication.driver.ResumeUsbPermission();
            if (retval == 0) {

            } else if (retval == -2) {
                Toast.makeText(Home2Activity.this, "获取权限失败!",
                        Toast.LENGTH_SHORT).show();
            }
        }
    }
    public void onDestroy() {
        isOpen = false;
        ReallyApplication.driver.CloseDevice();
        super.onDestroy();
    }
}
